<?php

/*
 * 游戏积分系统
 * 实现游戏内积分与外部商城同步机制
 */
class pointDB
{
    private $dbc;

    function __construct(DBC $dbc)
    {
        $this->dbc = $dbc;
    }

    /*
     * 获取积分值
     */
    public function GetPointCount($accunique,$account_id)
    {
        $sql = "SELECT top 3 * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
        $data = $this->dbc->fetchData($sql);
        if( !isArrayNotEmpty($data) )
        {
            $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES(1,$accunique,'" . $account_id . "',0,0,0,99999,getdate())";
            $this->dbc->execute($sql);
            $sql = "SELECT * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
            return $this->dbc->fetchData($sql);
        }else{
            return $data;
        }
    }


    /*
     * 购买消费积分商品  type:1 消费
     */
    public function PointBuyItem($accunique,$account_id,$needPoint,$itemIndex,$num,$type,$itemname)
    {
        $sql = "SELECT top 3 * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
        $data = $this->dbc->fetchData($sql);
        if( !isArrayNotEmpty($data) ){
            $result = array(
                'code' => 1,
                'pay' => false,
                'send' => false,
                'msg' => "没有账号数据"
            );
            return $result;
        }
        if( $data[0]['balance_point'] < $needPoint ){
            //余额不足
            $result = array(
                'code' => 1,
                'pay' => false,
                'send' => false,
                'msg' =>"余额不足"
            );
            return $result;
        }else{
            /*
             * 解释下，useing_point 代表消费  等于0代表增加t
             * all_point字段的含义是 不管增加点数还是减少点数 都是累积值
             * balance_point 是实际金额 与购买交互 购买减少  增加就增加
             * 这个逻辑是全程新增数据，查询和更改 均为insert 方式，以id_x倒叙累加
             */
            $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES('" . ( $data[0]['id_x'] + 1 ) . "',$accunique,'" . $account_id . "','" . $needPoint . "','" . ($data[0]['all_point'] + $needPoint ) . "','" . ( $data[0]['balance_point'] - $needPoint ) ."','" . $itemIndex . "',getdate())";
            $result_pay = $this->dbc->execute($sql);//这里已经消费了，数据已插入新的了
            $sql = "SELECT top 3 * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
            $data_after = $this->dbc->fetchData($sql);
            $after = ( $data_after[0]['balance_point'] + $needPoint );
            if(  $after == $data[0]['balance_point'] )//再次验证正常扣费了
            {
                //插入物品数据到用户
                $sql = "INSERT INTO TAccount..item_buy_info(accunique,account_id,product_id,ItemIndex,Item_count,Item_using,buy_dated) VALUES('" . $accunique . "','" . $account_id . "','139','" . $itemIndex . "','" . $num . "',3,getDate())";
                $result_send = $this->dbc->execute($sql);
                //写入插入物品数据的日志到item_log
                $user_ip = $_SERVER["REMOTE_ADDR"];
                if( $user_ip == "" )
                {
                    $user_ip = "0.0.0.0";
                }
                $sql = "SELECT top 3 * FROM TAccount..item_buy_info WHERE accunique = '" . $accunique . "' AND account_id = '" . $account_id . "' ORDER BY id_x DESC";
                $data_item_buy_infodata = $this->dbc->fetchData($sql);
                $sql = "insert into TAccount..item_buy_log(id_x,accunique,account_id,item_using,item_price,product_id,ItemIndex,Item_count,buy_dated,Ip_Address) values('" . $data_item_buy_infodata[0]['id_x'] . "','" . $accunique . "','" . $account_id . "',0,'". $needPoint . "','" . $itemIndex . " ','" . $itemIndex . "','". $num . "',getdate(),'" . $user_ip . "')";
                //echo $sql;
                $this->dbc->execute($sql);
                //写入消耗point的日志
                $sql = "INSERT INTO user_web_use_log(accunique,account_id,add_point,add_id_x,add_before_balance_point,add_after_balance_point,type,add_time,itemindex,itemname) VALUES('" . $accunique . "','" . $account_id . "',$needPoint,'" . ($data[0]['id_x'] + 1 ) . "','" . $data[0]['balance_point'] . "','" . ( $data[0]['balance_point'] - $needPoint ) . "','" . $type . "',getdate(),'" . $itemIndex . "','" . $itemname . "')";
                //echo $sql;
                $this->dbc->execute($sql);
            }else if( $after > $data[0]['all_point'] ){
                //扣积分异常 扣少了
            }else
            {
                //扣多了
            }
            if( ( $result_pay ) && ( $result_send ))
            {
                $result = array(
                    'code' => 0,
                    'pay' => $result_pay,
                    'send' => $result_send,
                    'msg' =>"交易完成"
                );
            }else if( !$result_pay)
            {
                $result = array(
                    'code' => 1,
                    'pay' => $result_pay,
                    'send' => $result_send,
                    'msg' =>"支付失败"
                );
            }else if( !$result_send )
            {
                $result = array(
                    'code' => 1,
                    'pay' => $result_pay,
                    'send' => $result_send,
                    'msg' =>"未发送物品"
                );
            }
            return $result;
        }
    }


    /*
     * 外部增加积分以及日志的生成
     * type：增加的方式： 1 充值增加途径   2 消费赠送  3 签到赠送 其余暂无
     */
    public function AddPoint($accunique,$account_id,$addpoint,$type)//$type 决定外部增加的方式
    {
        // insert payment_db..payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) values(@Count, @Accunique, @AccountID, 0, @allpoint+@point, @balance_point+@point, 99999, getdate())
        $sql = "SELECT top 3 * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
        //echo $sql;
        $data = $this->dbc->fetchData($sql);
        if( !isArrayNotEmpty($data) ){//没有获取到数据 写入一条
            $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES(1,$accunique,'" . $account_id . "',0,$addpoint,$addpoint,99999,getdate())";
            $frist_res =  $this->dbc->execute($sql);
            if( $frist_res )//如果成功记录日志
            {
                $sql = "INSERT INTO user_web_add_log(accunique,account_id,add_point,add_id_x,add_before_balance_point,add_after_balance_point,type,add_time) VALUES($accunique,'" . $account_id . "','" . $addpoint . "',1,0,'" . $addpoint . "','" . $type . "',getdate())";
                $this->dbc->execute($sql);
                $sql = "INSERT INTO exchange_point_info( Accunique, Account_id, change_point, change_Time ) values('" . $accunique . "', '" . $account_id . "', '" . $addpoint . "', getdate())";
                $this->dbc->execute($sql);
            }
            return $frist_res;
        }else{//有数据则改变
            //$sql = "UPDATE payment_point_info SET all_point = all_point + $addpoint , balance_point = balance_point + $addpoint WHERE accunique = $accunique AND id_x = '" . $data[0]['id_x'] . "'";
            $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES('" . ( $data[0]['id_x'] + 1 ) . "',$accunique,'" . $account_id . "',0,'" . ( $data[0]['all_point'] + $addpoint ) . "','" . ( $data[0]['balance_point'] + $addpoint ) . "',99999,getdate())";
            $res = $this->dbc->execute($sql);
            if( $res )//如果成功记录日志
            {
                $sql = "INSERT INTO user_web_add_log(accunique,account_id,add_point,add_id_x,add_before_balance_point,add_after_balance_point,type,add_time) VALUES($accunique,'" . $account_id . "',$addpoint,'" . ( $data[0]['id_x'] + 1 ) . "','" . $data[0]['balance_point'] . "','" . ( $data[0]['balance_point'] + $addpoint ) . "','" . $type . "',getdate())";
                //echo $sql;
                $this->dbc->execute($sql);
            }
        }
    }

    /*
     * 商城消费赠送 type增加渠道为2 走add log
     * API入口调用处设置比例
     */
    public function StoreSendPoint($accunique,$account_id,$sendpoint,$type)//type = 2
    {
        $res = array();
        $now_point = 0;
        if($sendpoint > 300 ){
            $sendpoint = 300;
        }
        $sql = "SELECT top 3 * FROM payment_point_info WHERE accunique = '" . $accunique . "' ORDER BY id_x DESC";
        $data = $this->dbc->fetchData($sql);
        //echo $sql;
        // var_dump($data);
        $sql = "SELECT sum(send_point) as Td_Already_Send_Point FROM Point_Store_Send__Log WHERE accunique = '" . $accunique . "' AND account_id = '" .$account_id ."' AND CONVERT(varchar(12) , getdate(), 111) = CONVERT(varchar(12) , send_time, 111)";
        //echo $sql;
        $data_Send = $this->dbc->fetchData($sql);
        if(isArrayNotEmpty($data_Send))
        {
            $Td_Already_Send_Point = $data_Send[0]['Td_Already_Send_Point'];
        }else{
            $Td_Already_Send_Point = 0;
            //$sql = "INSERT INTO Td_Already_Send_Point(accunique,account_id,send_point,send_time) VALUE('" . $accunique . "', '" . $account_id . "','" . $Td_Already_Send_Point . "',getdate())";
        }
        if( ( $sendpoint + $Td_Already_Send_Point ) > 300 )
        {
            $sendpoint = ( 300 - $Td_Already_Send_Point );
        }
        if( $sendpoint > 0 )
        {
            if( !isArrayNotEmpty($data) ){//没有获取到数据 写入一条
                $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES(1,$accunique,'" . $account_id . "',0,$sendpoint,$sendpoint,99999,getdate())";
                //echo $sql;
                $Send_result1 =  $this->dbc->execute($sql);
            }else{
                $sql = "INSERT INTO payment_point_info(id_x, accunique, account_id, using_point, all_point, balance_point, product_id, dated) VALUES('" . ( $data[0]['id_x'] + 1 ) . "',$accunique,'" . $account_id . "',0,'" . ( $data[0]['all_point'] + $sendpoint ) . "','" . ( $data[0]['balance_point'] + $sendpoint ) . "',99999,getdate())";
                //echo $sql;
                $Send_result2 = $this->dbc->execute($sql);
            }
        }else
        {
            $res['code'] = 2;
            $res['msg'] = "已达到今日赠送上限";
            return $res;
        }
        if( $Send_result1 )
        {
            $sql = "INSERT INTO Point_Store_Send__Log(accunique,account_id,send_point,send_time) VALUES('" . $accunique . "', '" . $account_id . "','" . $sendpoint . "',getdate())";
            $this->dbc->execute($sql);
            $sql = "INSERT INTO user_web_add_log(accunique,account_id,add_point,add_id_x,add_before_balance_point,add_after_balance_point,type,add_time) VALUES($accunique,'" . $account_id . "',$sendpoint,'1','0','" . $sendpoint . "','" . $type . "',getdate())";
            $this->dbc->execute($sql);
            $sql = "INSERT INTO exchange_point_info( Accunique, Account_id, change_point, change_Time ) values('" . $accunique . "', '" . $account_id . "', '" . $sendpoint . "', getdate())";
            $this->dbc->execute($sql);
            $res['code'] = 0;
            $res['msg'] = "赠送成功";

        }else if( $Send_result2 ){
            $sql = "INSERT INTO Point_Store_Send__Log(accunique,account_id,send_point,send_time) VALUES('" . $accunique . "', '" . $account_id . "','" . $sendpoint . "',getdate())";
            $this->dbc->execute($sql);
            $sql = "INSERT INTO user_web_add_log(accunique,account_id,add_point,add_id_x,add_before_balance_point,add_after_balance_point,type,add_time) VALUES($accunique,'" . $account_id . "',$sendpoint,'" . ( $data[0]['id_x'] + 1 ) . "','" . $data[0]['balance_point'] . "','" . ( $data[0]['balance_point'] + $sendpoint ) . "','" . $type . "',getdate())";
            $this->dbc->execute($sql);
            $sql = "INSERT INTO exchange_point_info( Accunique, Account_id, change_point, change_Time ) values('" . $accunique . "', '" . $account_id . "', '" . $sendpoint . "', getdate())";
            $this->dbc->execute($sql);
            $res['code'] = 0;
            $res['msg'] = "赠送成功";
        }else
        {
            $res['code'] = 1;
            $res['msg'] = "赠送失败";
        }
        return $res;


    }


    /*
     *每日签到送积分
     */
    public function qiandao($accunique,$account_id)
    {
        $today = date("Y/m/d");
        $nowtime = time();
        $res = array();
        $sql = "SELECT top 3 * FROM point_qiandao_remeber WHERE accunique = '" . $accunique . "' AND account_id = '" . $account_id . "' AND qiandao_riqi = '" . $today . "'" ;
        //echo $sql;
        $data = $this->dbc->fetchData($sql);
        if(isArrayNotEmpty($data))
        {
            if ($data[0]['qdcount'] >= 5 )
            {
                $res['code'] = 2;
                $res['time'] = 0;
                $res['count'] = $data[0]['qdcount'];
                $res['msg'] = "签到次数已达今日上限";
                return $res;
            }
            if($nowtime - ( $data[0]['curtime'] ) <= 7200 )
            {
                $res['code'] = 1;
                $res['time'] = 7200-($nowtime - ($data[0]['curtime']));
                $res['count'] = $data[0]['qdcount'];
                $res['msg'] = "签到时间不足2小时";
                return $res;
            }
            $sql = "UPDATE point_qiandao_remeber SET beftime = curtime , curtime = '" . $nowtime . "' , qdcount = qdcount + 1 WHERE accunique = '" . $accunique . "' AND account_id = '" . $account_id . "'";
            $this->dbc->execute($sql);
            $res['code'] = 0;
            $res['time'] = 0;
            $res['count'] = $data[0]['qdcount'];
            $res['msg'] = "签到成功,请2个小时后再来";
        }else {
            $sql = "INSERT INTO point_qiandao_remeber(accunique,account_id,qdcount,beftime,curtime,qiandao_riqi) VALUES('" . $accunique . "' , '" . $account_id . "' , 1 , 0 , '" . $nowtime . "' , '" . $today . "')";
            //echo $sql;
            $firstqd_res = $this->dbc->execute($sql);
            if ( $firstqd_res )
            {
                $res['code'] = 0;
                $res['time'] = 0;
                $res['count'] = 0;
                $res['msg'] = "签到成功,请2个小时候再来";
            }
        }
        return $res;
    }



    ///列表页面商品相关信息
    /**
     * 获得商品列表
     * @param type $type
     * @param type $start
     * @param type $limit
     * @return type
     */
    public function getItem($type, $start, $limit) {
        if (!is_numeric($start)) {
            $start = 0;
        }
        if (!is_numeric($limit)) {
            $limit = 10;
        }
        if ($type == "all" || $type == "") {
            $sql = "SELECT TOP " . $limit . " * FROM Point_ItemInfo WHERE id_x NOT IN(SELECT TOP " . $start . " id_x FROM ItemInfo WHERE Status = 1) AND Status = 1 ORDER BY UpdateTime DESC;";
        } else {
            $sql = "SELECT TOP " . $limit . " * FROM Point_ItemInfo WHERE Type = '" . $type . "' AND id_x NOT IN(SELECT TOP " . $start . " id_x FROM ItemInfo WHERE Type = '" . $type . "' AND Status = 1) AND Status = 1 ORDER BY UpdateTime DESC;";
        }
        return $this->dbc->fetchData($sql);
    }

    /**
     *
     * 每月已购买数量获取
     */
    public function getAlreadyBuyCount($accunique,$itemNo)
    {
        $nowtime = time();
        $month_firstday = date('Y-m-01', $nowtime);
        $month_lastday = date('Y-m-d', strtotime("$month_firstday +1 month -1 day"));
        $sql = "SELECT * FROM TAccount..AccountMoneyDetail_Point WHERE itemNo = '" . $itemNo . "' AND AccUnique = '" . $accunique . "' AND DATEDIFF(day, '" . $month_firstday . "' , UpdateTime) >= 0 AND DATEDIFF(day,UpdateTime, '" . $month_lastday . "') >= 0";
        //echo $sql;
        return $this->dbc->fetchData($sql);
    }

    /**
     * 获得一批商品编号对应的商品信息
     * @param type $itemNos
     * @return type
     */
    public function getItemByNo($itemNos) {
        $sql = "SELECT * FROM Point_ItemInfo WHERE ItemNo IN(" . $itemNos . ") AND Status = 1;";
        return $this->dbc->fetchData($sql);
    }

    /**
     * 根据商品ID获得商品信息
     * @param type $id
     * @return type
     */
    public function getItemById($id) {
        $sql = "SELECT * FROM Point_ItemInfo WHERE id_x = " . $id;
        return $this->dbc->fetchData($sql);
    }

    /**
     * 根据类型获得总的商品数量
     * @param type $type
     * @return type
     */
    public function getItemNumber($type) {
        if ($type == "all" || $type == "") {
            $sql = "SELECT COUNT(id_x) AS totalNumber FROM Point_ItemInfo WHERE Status = 1;";
        } else {
            $sql = "SELECT COUNT(id_x) AS totalNumber FROM Point_ItemInfo WHERE Type = '" . $type . "' AND  Status = 1;";
        }

        $data = $this->dbc->fetchData($sql);
        if (isArrayNotEmpty($data)) {
            return $data[0]['totalNumber'];
        }
        return 0;
    }

    /**
     * 修改商品
     * @param type $idx
     * @param type $itemNo
     * @param type $itemName
     * @param type $price
     * @param type $type
     * @param type $imageUrl
     * @return type
     */
    public function modifyItem($idx, $itemNo, $itemName, $price, $type, $imageUrl = "") {
        if ($imageUrl == "") {
            $sql = "UPDATE Point_ItemInfo SET ItemNo = '" . $itemNo . "',ItemName = '" . $itemName
                . "',Price = '" . $price . "',Type = '" . $type . "',UpdateTime = getDate() FROM Point_ItemInfo WHERE id_x = " . $idx . ";";
        } else {
            $sql = "UPDATE Point_ItemInfo SET ItemNo = '" . $itemNo . "',ItemName = '" . $itemName
                . "',Price = '" . $price . "',Type = '" . $type . "',UpdateTime = getDate(),ImageUrl = '" . $imageUrl . "' FROM Point_ItemInfo WHERE id_x = " . $idx . ";";
        }
        return $this->dbc->execute($sql);
    }

    /**
     * 新增
     * @param type $itemNo
     * @param type $itemName
     * @param type $price
     * @param type $type
     * @param type $imageUrl
     * @return type
     */
    public function createItem($itemNo, $itemName, $price, $type, $imageUrl = "") {
        $sql = "insert into Point_ItemInfo(ItemNo,ItemName,Price,Type,UpdateTime,ImageUrl,status) values('" . $itemNo . "','" . $itemName
            . "','" . $price . "','" . $type . "', getDate(),'" . $imageUrl . "',1)";
        return $this->dbc->execute($sql);
    }

    /**
     * 删除商品（状态改成下线）status 状态：1=上线  0=下线
     * @param type $idx
     * @return type
     */
    public function deleteItem($idx) {
        $sql = "UPDATE Point_ItemInfo SET Status = 0 WHERE id_x = " . $idx . ";";
        return $this->dbc->execute($sql);
    }


}
?>